{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.变量的执行解析状态"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "20\n"
     ]
    }
   ],
   "source": [
    "# 默认值是在定义过程中在函数定义处计算的,并且默认值只会执行一次\n",
    "i=10\n",
    "def test(arg=i):\n",
    "    print(arg)\n",
    "i=20\n",
    "test()\n",
    "\n",
    "#自由变量的名称解析发生于运行时而不是编译时\n",
    "i=10\n",
    "def test():\n",
    "    print(i)\n",
    "i=20\n",
    "test()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.作用域和命名空间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After local assignment: test spam\n",
      "After nonlocal assignment: nonlocal spam\n",
      "After global assignment: nonlocal spam\n",
      "In global scope: global spam\n"
     ]
    }
   ],
   "source": [
    "def scope_test():\n",
    "    def do_local():\n",
    "        spam =\"local spam\"\n",
    "\n",
    "    def do_nonlocal():\n",
    "        nonlocal spam\n",
    "        spam =\"nonlocal spam\"\n",
    "\n",
    "    def do_global():\n",
    "        global spam #这里的spam是scope_test外的变量，并不是scope_test内部的变量\n",
    "        spam =\"global spam\"\n",
    "    \n",
    "    spam =\"test spam\"\n",
    "    \n",
    "    do_local()\n",
    "    print(\"After local assignment:\", spam)\n",
    "    do_nonlocal()\n",
    "    print(\"After nonlocal assignment:\", spam)\n",
    "    do_global()\n",
    "    print(\"After global assignment:\", spam)\n",
    "\n",
    "scope_test()\n",
    "print(\"In global scope:\", spam)\n",
    "\n",
    "#nonlocal 赋值会改变 scope_test对 spam 的绑定，而 global 赋值会改变模块层级的绑定。"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
  },
  "kernelspec": {
   "display_name": "Python 3.7.4 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
